package com.zhentao.config;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {
    /**
     * 发送GET请求，调用微信接口
     */
    /**
     * 发送GET请求，调用微信接口
     * 1. 通过HttpClients.createDefault()创建可关闭的HttpClient实例
     * 2. 构造HttpGet对象并传入目标URL
     * 3. 执行请求获得CloseableHttpResponse
     * 4. 使用EntityUtils.toString将响应体转换为字符串返回
     * 5. try-with-resources自动关闭httpClient，释放连接资源
     * 6. 若发生IOException，封装为RuntimeException向上抛出，提示“HTTP请求失败”
     */
    public static String doGet(String url) {
        // 创建HttpClient对象
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpGet对象并设置URI
            HttpGet httpGet = new HttpGet(url);
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 处理响应
            return EntityUtils.toString(response.getEntity());
            // 释放资源
        } catch (IOException e) {
            // 处理异常
            throw new RuntimeException("HTTP请求失败", e);
        }
    }
}
